<template>
    <div class="container">
        <el-table :data="tableData" height="calc(100vh - 426px)">
            <el-table-column prop="title" label="规则名称" width="180">
                <template #default="{ row }">
                    <renderOverflowTootip :value="row.title" />
                </template>
            </el-table-column>
            <el-table-column v-if="props.replyType === 'groupChat'" prop="chatType" label="关联群聊/个" width="180">
                <template #default="{ row }">
                    {{ row.chatType === 1 ? '全部' : row.chatNum }}
                </template>
            </el-table-column>
            <el-table-column prop="keywordNum" label="关键词/个" min-width="120">
                <template #default="{ row }">
                    <renderOverflowTootip :value="row.keywordNum" />
                </template>
            </el-table-column>
            <el-table-column prop="speechCraftNum" label="话术/条" min-width="120">
                <template #default="{ row }">
                    <renderOverflowTootip :value="row.speechCraftNum" />
                </template>
            </el-table-column>
            <el-table-column prop="replyType" label="回复方式" min-width="120">
                <template #default="{ row }">
                    <renderOverflowTootip :value="row.replyType === 1 ? '全部回复' : '随机回复一条'" />
                </template>
            </el-table-column>
            <el-table-column prop="enableTime" label="启用时段" min-width="170">
                <template #default="{ row }">
                    <span v-if="!row.enableTime || row.enableTime.type === 1">全部时段</span>
                    <el-tooltip v-else :disabled="row.enableTime.time.length < 3" effect="dark" placement="top-start">
                        <template #content>
                            <div v-html="computedEnableTimeValue(row.enableTime).join('<br />')" class="table-enable-time">
                            </div>
                        </template>
                        <div>
                            <span
                                class="table-enable-time"
                                v-html="computedEnableTimeValue(row.enableTime).slice(0, 2).join('<br />')"
                            />
                            <span v-if="row.enableTime.time.length >= 3" >...</span>
                        </div>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="repliesNums" label="回复次数" width="160">
                <template #header>
                    <el-tooltip placement="top-start" popper-class="render-tootip" effect="dark"
                        content="在启用时段，发送满足触发规则的关键词，并满足重发限制的实际回复次数">
                        <div class="header-icon">
                            <div class="header-label">回复次数</div>
                            <el-icon>
                                <QuestionFilled />
                            </el-icon>
                        </div>
                    </el-tooltip>
                </template>
                <template #default="{ row }">
                    <renderOverflowTootip :value="row.repliesNums" />
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="200">
                <template #default="{ row }">
                    <renderOverflowTootip :value="row.createdAt" />
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                    <el-switch :model-value="row.status" :loading="row.statusLoading" :active-value="1" :inactive-value="2"
                        @click="handleChangeStatus(row)" />
                </template>
            </el-table-column>
            <el-table-column fixed="right" prop="operate" label="操作" width="160">
                <template #default="{ row }">
                    <el-tooltip v-if="row.status === 1" effect="dark" placement="top-start" content="只有关闭状态才可以编辑">
                        <div class="tootip-button el-button is-link">
                            <el-button disabled type="primary" link>
                                编辑
                            </el-button>
                        </div>
                    </el-tooltip>
                    <el-button v-else type="primary" link @click="toEditReplay(row)">
                        编辑
                    </el-button>
                    <el-button type="primary" link @click="handleDelete(row)">
                        删除
                    </el-button>
                    <el-button type="primary" link @click="handleShowDetail(row)">
                        明细
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:currentPage="state.page" v-model:pageSize="state.page_size" background
            layout="total, prev, pager, next, sizes, jumper" :total="state.total" :page-sizes="[15, 30, 50, 100]"
            @sizeChange="onSizeChange" @currentChange="onCurrentChange" />
        <ReplyDetailDialog v-model="detailVisiable" :type="props.replyType" :id="currentId" />
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";

import {
    getSmartReplySingleList,
    toggleSmartReplySingleStatus,
    deleteSmartReplySingle,
    getSmartReplyChatList,
    toggleSmartReplyChatStatus,
    deleteSmartReplyChat,
    ISingReplyFormData
} from '@renderer/ajax/api/smartReply'

import renderOverflowTootip from './tableColumnRender/render-overflow-tootip.vue'
import ReplyDetailDialog from './replyDetailDialog/replyDetailDialog.vue'

const router = useRouter()
const emit = defineEmits(["submit", "reset", "createRule", 'update:loading']);
const props = withDefaults(defineProps<{
    replyType: string;
    fetchParams: ISingReplyFormData,
    loading: boolean
}>(), {
    fetchParams: () => ({
        titleKeyword: '',
        createAt: [],
        status: 1,
        replyType: 1,
    }),
    loading: false
});
/* ----------------------------搜索参数-start---------------------------- */
const state = reactive({
    title: "",
    create_time: [],
    task_type: undefined,
    reply_mode: undefined,
    page: 1,
    page_size: 15,
    total: 0,
});

const onSizeChange = (v: number) => {
    state.page_size = v;
    getData();
};
const onCurrentChange = (v: number) => {
    state.page = v;
    getData();
};
/* ----------------------------搜索参数-end---------------------------- */

/* ----------------------------表格内容-start---------------------------- */

const tableData = reactive([]);
/** 表格loading */
const getData = async () => {
    try {
        emit('update:loading', true)
        const getListApi = props.replyType === 'privateChat' ? getSmartReplySingleList : getSmartReplyChatList
        const res = await getListApi(state)
        tableData.length = 0
        tableData.push(...(res?.data || []))
        state.total = res?.total || 0;
    } finally {
        emit('update:loading', false)
    }
}

watch(
    () => props.fetchParams,
    () => {
        Object.assign(state, { ...props.fetchParams, page: 1, page_size: 15, total: 0, })
        getData()
    },
    { deep: true, immediate: true }
)

/**
 * 计算当前行的启用时段文本内容
 */
const computedEnableTimeValue = (enableTime) => {
    return enableTime.time.map(({ beginTime, endTime }) => {
        return `${beginTime ? dayjs(beginTime).format('HH:mm:ss') : '--'} ~ ${endTime ? dayjs(endTime).format('HH:mm:ss') : '--'}`
    })
}
/* ----------------------------表格内容-end---------------------------- */

/**
 * 更改状态
 * @param row 
 */
const handleChangeStatus = async (row) => {
    if (row.statusLoading) return
    await handleConfirmMessage(`确定要${row.status === 1 ? '关闭' : '开启'}此规则吗？`);
    try {
        row.statusLoading = true
        const toggleApi = props.replyType === 'privateChat' ? toggleSmartReplySingleStatus : toggleSmartReplyChatStatus
        await toggleApi({
            id: row.id,
            status: row.status === 1 ? 2 : 1
        })
        getData()
    } finally {
        row.statusLoading = false
    }
}

/**
 * 删除
 * @param row 
 */
const handleDelete = async (row) => {
    await handleConfirmMessage(`确定要删除此规则吗？`);
    const delApi = props.replyType === 'privateChat' ? deleteSmartReplySingle : deleteSmartReplyChat
    // 删除选中的行
    await delApi({ id: row.id })
    ElMessage.success('删除成功')
    getData()
}

/**
 * 打开编辑页面
 */
const toEditReplay = (row) => {
    router.push({
        path: '/smartReply/edit',
        query: {
            type: props.replyType,
            pageType: 'edit',
            id: row.id
        }
    })
}

const detailVisiable = ref(false);
const currentId = ref()
/**
 * 打开明细弹窗
 */
const handleShowDetail = (row) => {
    currentId.value = row.id
    detailVisiable.value = true;
}

// 二次确认弹窗
const handleConfirmMessage = async (title) => {
    return await ElMessageBox.confirm(
        title,
        '提示',
        {
            icon: '',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
}


defineExpose({
    refresh: getData
})
</script>
<style lang="scss" scoped>
.el-button.is-link {
    padding: 0;
}

.header-icon {
    .header-label {
        display: inline-block;
        vertical-align: middle;
    }

    .el-icon {
        margin-left: 2px;
        vertical-align: middle;
    }
}

:global(.table-enable-time) {
    font-family: Arial, Helvetica, sans-serif;
    cursor: pointer;
}

.tootip-button {
    display: inline-block;
}
</style>
